package cn.edu.swust.adressbook.service.impl;

import android.content.Context;

import java.util.List;

import cn.edu.swust.adressbook.bean.Contact;
import cn.edu.swust.adressbook.bean.Group;
import cn.edu.swust.adressbook.dao.ContactDao;
import cn.edu.swust.adressbook.dao.GroupDao;


public class GroupServiceImpl extends BaseServiceImpl<Group> {

    public GroupServiceImpl(Context context) {
        super(context);
    }

    @Override
    public List<Group> getAll() {
        List<Group> list = daoSession.getGroupDao().queryBuilder().orderDesc(GroupDao.Properties.Id).list();
        for(int i=0;i<list.size();i++){
            int count = getGroupCountSize(list.get(i).getId());
            list.get(i).setContactCount(count);
        }
        return list;
    }

    @Override
    public void update(Group group) {
        group.setContactCount(getGroupCountSize(group.getId()));
        super.update(group);
    }

    private int getGroupCountSize(long id) {
        return daoSession.getContactDao().queryBuilder().where(ContactDao.Properties.GroupId.eq(id)).list().size();
    }

    @Override
    public void delete(Group group) {
        updateContacts(group.getId());
        super.delete(group);
    }

    @Override
    public Group get(Long id) {
        return daoSession.getGroupDao().load(id);
    }

    private void updateContacts(long id) {
        List<Contact> list = daoSession.getContactDao().queryBuilder()
                            .where(ContactDao.Properties.GroupId.eq(id)).list();
        for (Contact item : list) {
            item.setGroupId(null);
            daoSession.update(item);
        }
    }
}
